// Copyright (c) 2025, qiushike and contributors
// For license information, please see license.txt


frappe.require([
    '/assets/light_mes/js/qz-tray.bundle.js',
    '/assets/light_mes/js/jsrsasign-all-min.bundle.js',
    '/assets/light_mes/js/sign-message.bundle.js'
]);

frappe.ui.form.on('Tracking Number', {
    onload(frm){

    },
    print: function (frm) {
        frappe.db.get_doc(frm.doctype, frm.doc.name).then(doc => {
            if (doc.is_printed == 1) {
                frappe.throw({
                    title: __("Doc Already Printed"),
                    message: __("Doc Already Printed. Please reload the page."),
                    indicator: 'red'
                });
            }
            frappe.dom.freeze(__('Printing'));
            //frappe.db.get_doc('POS Profile', frm.doc.pos_profile).then(profile => {

            //    if (profile.qz_print == 1) {
                    // To fetch qz_key from site config
            frappe.run_serially([
                () => {
                    frappe.call({
                        method: "light_mes.qz_print_api.qz_certificate",
                        callback: function (response) {
                            if (response.message) {
                                var qzKey = response.message;
                                qz.security.setCertificatePromise(function (resolve, reject) {
                                    //Preferred method - from server
                                    fetch("/files/" + qzKey, { cache: 'no-store', headers: { 'Content-Type': 'text/plain' } })
                                    .then(
                                        (data)=> {
                                            console.log("certificate data");
                                            console.log(data);
                                            data.ok ? resolve(data.text()) : reject(data.text()); 
                                    });
                                });
                            }
                        }
                    });
                },
                () => {

                    if (!qz.websocket.isActive()){
                        let qz_host = frappe.is_mobile()? "192.168.3.99":"192.168.3.99";
                        qz.websocket.connect({ host: qz_host})
                        .then(() => {
                            // test();
                            //printWithQZTray(frm, r);
                        })
                        .catch((error) => {
                            // Handle connection error
                            console.error("Error connecting to QZ Tray:", error);
                            frappe.dom.unfreeze();
                            frappe.throw({
                                message: __("Printing Failed: Error connecting to QZ Tray")
                            });
                        });
                    }
                },
                () => {
                    frappe.call({
                        method: "frappe.www.printview.get_html_and_style",
                        args: {
                            doc: frm.doctype,
                            name: frm.docname,
                            print_format: "追踪号标签",
                            //_lang: 'en',
                        },
                        callback: function (r) {
                            if (qz.websocket.isActive()) {
                                // Use the existing connection to print
                                printWithQZTray(frm, r);
                            }
                        },
                    });
                },
            ]);                                
        })
    }
})

function printWithQZTray(frm, r) {
    qz.printers.getDefault()
        .then((printer) => {
            var htmlcontent = r.message.html;
            var data = [{
                type: 'html',
                format: 'plain',
                data: htmlcontent
            }];

            var config = qz.configs.create(printer);
            qz.print(config, data)
                .then(function () {
                    frappe.db.set_value(frm.doctype, frm.docname, "is_printed", 1);
                    cur_frm.set_value('is_printed', 1);
                    frappe.dom.unfreeze();
                    frappe.show_alert({ message: __('Printed'), indicator: 'green' });
                })
                .catch(function (error) {
                    // Handle printing error
                    console.error("Error printing with QZ Tray:", error);
                    frappe.dom.unfreeze();
                    frappe.throw({
                        message: __("Printing Failed: Error printing with QZ Tray")
                    });
                });
        })
        .catch(function (error) {
            // Handle printer lookup error
            console.error("Error looking up printer:", error);
            frappe.dom.unfreeze();
            frappe.throw({
                message: __("Printing Failed: Error looking up printer")
            });
        });
} 